# _*_ coding:utf-8 _*_
# @author : Joyamon
# @time : 2022-11-11 15:14
# @file : makeToken.py

# https://blog.csdn.net/t8116189520/article/details/122673112
import datetime
import jwt
from flask import request, g, current_app, jsonify
from jwt import exceptions
from functools import wraps

from exts.xjson import json_success, json_error
from settings import SECRET_KEY

headers = {
    'typ': 'jwt',
    'alg': 'HS256'
}

# 密钥
SALT = '123456'


def create_token(username):
    # 构造payload
    payload = {
        'username': username,
        # 'password': password,  # 自定义用户ID
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)  # 超时时间
    }
    result = jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers).decode('utf-8')
    return result


def verify_jwt(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        return payload
    except exceptions.ExpiredSignatureError:
        return json_error(message='token已失效')
    except jwt.DecodeError:
        return json_error(message='token认证失败')
    except jwt.InvalidTokenError:
        return json_error(message='非法的token')


def login_required(func):
    """登录校验装饰器
    :param func:函数名
    :return: 闭包函数名
    """
    @wraps(func)
    def decorated(*args, **kwargs):
        token = request.headers.get("Authorization")
        if verify_jwt(token):
            return func(*args, **kwargs)
        else:
            return jsonify({'code': 401, 'msg': '您还未登录，请先登录后进行操作!'})
    return decorated
